package com.kfdx;

import javax.imageio.ImageIO;
import javax.imageio.ImageWriteParam;
import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test {
    static int i = 0;

        public static void main(String[] args) throws IOException {
            String folderPath = "D:\\新建文件夹 (2)\\封闭管理信息第二批";  // 替换为您的文件夹路径
            processFileNames(folderPath);
        }

        public static void processFileNames(String folderPath) throws IOException {
            File folder = new File(folderPath);
            File[] files = folder.listFiles();
            if (files!= null) {
                for (File file : files) {
                    if (file.isFile()) {

                        String fileName = file.getName();
                        if(!(fileName.endsWith(".jpg") || fileName.endsWith(".png") || fileName.endsWith(".JPG") || fileName.endsWith(".PNG") || fileName.endsWith(".JPEG") || fileName.endsWith(".jpeg"))){
                            System.out.println("过滤掉的文件：**********************************************************************************************************************************"+fileName);
                            continue;
                        }
                        System.out.println("压缩源文件目录："+file.getAbsolutePath());
//                        File sourceFile = new File(file.getAbsolutePath());
//                        BufferedImage sourceImage = ImageIO.read(sourceFile);

                        // 调整分辨率
                        resizeImage(file.getAbsolutePath(), file.getAbsolutePath(), 640, 430);
                        String newFileName = "";
                        newFileName = removeChineseCharacters(fileName);
                        newFileName = removeJpg(newFileName);
//                        String path = folderPath+"\\修改后\\";
//                        File file2 = new File(path);
//                        if(!file2.exists()){
//                            file2.mkdir();
//                        }
                        File newFile = new File(folderPath+"\\"+newFileName);
                        file.renameTo(newFile);
//                        compressImage(file.getAbsolutePath(),newFile.getAbsolutePath());
                        i++;
                        System.out.println("Processed: " + newFileName+"**********total:"+i);
                    }else{
                        processFileNames(file.getAbsolutePath());
                    }
                }
            }
        }

        public static String removeChineseCharacters(String str) {
            StringBuilder result = new StringBuilder();
            for (char c : str.toCharArray()) {
                if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' || c == '.' ) {
                    result.append(c);
                }
            }
            return result.toString();
        }

    public static String removeJpg(String str) {
        StringBuilder result = new StringBuilder();
        str = str.replaceAll(".jpg.jpg",".jpg");
        str = str.replaceAll(".jpg.png",".png");
        str = str.replaceAll(".png.png",".png");
        str = str.replaceAll(".JPG.jpg",".jpg");
        str = str.replaceAll(".JPG.png",".png");
        str = str.replaceAll(".JPG.PNG",".png");
        str = str.replaceAll(".jpg.PNG",".png");

        str = str.replaceAll(".jpg.JPG",".jpg");
//        str = str.replaceAll(".png",".jpg");
        str = str.replaceAll(".PNG",".png");


//        str = str.replaceAll(" ","");

        return str;
    }

    public static void compressImage(String sourceImagePath, String destinationImagePath) {
        try {
            System.out.println("压缩源文件目录："+destinationImagePath);
            File sourceFile = new File(destinationImagePath);
            BufferedImage sourceImage = ImageIO.read(sourceFile);

            // 调整分辨率
            BufferedImage resizedImage = new BufferedImage(640, 430, BufferedImage.TYPE_INT_RGB);
            Graphics2D g = resizedImage.createGraphics();
            g.drawImage(sourceImage, 0, 0, 640, 430, null);
            g.dispose();

//            // 获取支持 JPEG 格式的写入器
//            String s = sourceImagePath.substring(sourceImagePath.lastIndexOf(".")+1,sourceImagePath.length());
//            System.out.println("文件结尾："+s);
//            ImageWriter writer = ImageIO.getImageWritersByFormatName(s).next();
//            ImageWriteParam param = writer.getDefaultWriteParam();
//            param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
//
//            // 循环压缩，直到文件大小小于 1.5M
//            float quality = 1.0f;
//            FileOutputStream fos = new FileOutputStream(destinationImagePath);
//            ImageOutputStream ios = ImageIO.createImageOutputStream(fos);
//            writer.setOutput(ios);
//
//            long fileSize = 0;
//            do {
//                param.setCompressionQuality(quality);
//                writer.write(null, new javax.imageio.IIOImage(resizedImage, null, null), param);
//                fileSize = new File(destinationImagePath).length();
//                quality -= 0.1f;  // 逐步降低质量以减小文件大小
//            } while (fileSize > 1500000 && quality >= 0.1f);

//            ios.close();
//            writer.dispose();
//            sourceFile.delete();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void resizeImage(String inputPath, String outputPath, int newWidth, int newHeight) {
        try {
            // 加载图片
            BufferedImage image = ImageIO.read(new File(inputPath));

            // 调整分辨率
            Image resizedImage = image.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);

            // 保存图片
            BufferedImage outputImage = new BufferedImage(newWidth, newHeight, image.getType());
            Graphics2D graphics2D = outputImage.createGraphics();
            graphics2D.drawImage(resizedImage, 0, 0, null);
            graphics2D.dispose();
            ImageIO.write(outputImage, "jpg", new File(outputPath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    }
